import React, { useState, useEffect } from 'react';
import { Table, Tabs, DatePicker, Card, message, Statistic, Row, Col, Typography } from 'antd';
import { rankingService } from '../services/rankingService';
import locale from 'antd/es/date-picker/locale/zh_CN';
import dayjs from 'dayjs';

const { TabPane } = Tabs;

const Ranking = () => {
  const [selectedDate, setSelectedDate] = useState(dayjs());
  const [loading, setLoading] = useState(false);
  const [rankings, setRankings] = useState({
    companion: [],
    dispatch: [],
    receptionist: []
  });

  const columns = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
    },
    { title: '姓名', dataIndex: 'name', key: 'name' },
    { title: '订单数', dataIndex: 'orderCount', key: 'orderCount' },
    { 
      title: '总流水', 
      dataIndex: 'amount', 
      key: 'amount',
      render: (value) => `¥${value?.toFixed(2) || '0.00'}`
    },
    {
      title: '实际收入',
      dataIndex: 'actualIncome',
      key: 'actualIncome',
      render: (value) => `¥${value?.toFixed(2) || '0.00'}`
    },
    {
      title: '平均订单金额',
      dataIndex: 'averageOrderAmount',
      key: 'averageOrderAmount',
      render: (value) => `¥${value?.toFixed(2) || '0.00'}`
    },
    {
      title: '团队抽成',
      dataIndex: 'totalGroupCommission',
      key: 'totalGroupCommission',
      render: (value) => `¥${value?.toFixed(2) || '0.00'}`
    }
  ];

  const calculateTotalAmount = (data) => {
    return data.reduce((sum, item) => sum + (item.amount || 0), 0);
  };

  const calculateTotalActualIncome = (data) => {
    return data.reduce((sum, item) => sum + (item.actualIncome || 0), 0);
  };

  const calculateTotalGroupCommission = (data) => {
    return data.reduce((sum, item) => sum + (item.totalGroupCommission || 0), 0);
  };

  const fetchRankings = async (date) => {
    const year = date.year();
    const month = date.month() + 1;
    setLoading(true);

    try {
      const [companion, dispatch, receptionist] = await Promise.all([
        rankingService.getCompanionRanking(year, month),
        rankingService.getDispatchRanking(year, month).catch(() => []),
        rankingService.getReceptionistRanking(year, month).catch(() => [])
      ]);

      setRankings({
        companion: companion || [],
        dispatch: dispatch || [],
        receptionist: receptionist || []
      });
    } catch (error) {
      message.error('获取排名数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRankings(selectedDate);
  }, [selectedDate]);

  const handleDateChange = (date) => {
    if (date) {
      setSelectedDate(date);
    }
  };

  const renderStatistics = (data) => (
    <Row gutter={16} style={{ marginBottom: 16 }}>
      <Col span={6}>
        <Card>
          <Statistic
            title="总订单数"
            value={data.reduce((sum, item) => sum + (item.orderCount || 0), 0)}
            suffix="单"
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="总流水"
            value={calculateTotalAmount(data)}
            precision={2}
            prefix="¥"
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="总实际收入"
            value={calculateTotalActualIncome(data)}
            precision={2}
            prefix="¥"
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="总团队抽成"
            value={calculateTotalGroupCommission(data)}
            precision={2}
            prefix="¥"
          />
        </Card>
      </Col>
    </Row>
  );

  const renderTopRanker = (data, title) => {
    if (!data || data.length === 0) return null;
    const topRanker = data[0];
    return (
      <Card title={title} style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Statistic title="姓名" value={topRanker.name} />
          </Col>
          <Col span={8}>
            <Statistic title="订单数" value={topRanker.orderCount} suffix="单" />
          </Col>
          <Col span={8}>
            <Statistic 
              title="总流水" 
              value={topRanker.amount} 
              precision={2} 
              prefix="¥" 
            />
          </Col>
        </Row>
        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col span={8}>
            <Statistic 
              title="实际收入" 
              value={topRanker.actualIncome} 
              precision={2} 
              prefix="¥" 
            />
          </Col>
          <Col span={8}>
            <Statistic 
              title="平均订单金额" 
              value={topRanker.averageOrderAmount} 
              precision={2} 
              prefix="¥" 
            />
          </Col>
          <Col span={8}>
            <Statistic 
              title="团队抽成" 
              value={topRanker.totalGroupCommission} 
              precision={2} 
              prefix="¥" 
            />
          </Col>
        </Row>
      </Card>
    );
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <div style={{ marginBottom: '16px' }}>
          <DatePicker
            picker="month"
            onChange={handleDateChange}
            locale={locale}
            value={selectedDate}
            style={{ width: 200 }}
          />
        </div>

        <Tabs defaultActiveKey="companion">
          <TabPane tab="陪玩排名" key="companion">
            {renderTopRanker(rankings.companion, "陪玩第一名")}
            {renderStatistics(rankings.companion)}
            <Table
              columns={columns}
              dataSource={rankings.companion}
              loading={loading}
              rowKey="id"
            />
          </TabPane>
          <TabPane tab="派单排名" key="dispatch">
            {renderTopRanker(rankings.dispatch, "派单第一名")}
            {renderStatistics(rankings.dispatch)}
            <Table
              columns={columns}
              dataSource={rankings.dispatch}
              loading={loading}
              rowKey="id"
            />
          </TabPane>
          <TabPane tab="接待排名" key="receptionist">
            {renderTopRanker(rankings.receptionist, "接待第一名")}
            {renderStatistics(rankings.receptionist)}
            <Table
              columns={columns}
              dataSource={rankings.receptionist}
              loading={loading}
              rowKey="id"
            />
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default Ranking;